package com.jinbaoty.recyclebins.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinbaoty.recyclebins.server.ResponseData;
import com.jinbaoty.recyclebins.utils.Utils;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;
import okio.Timeout;

public class DefaultCallback extends StringCallback {

    private String response;
    private StringBuilder loggerInfo = new StringBuilder();
    public void addLog(String msg){
        loggerInfo.append(msg+"\n");
    }
    public void printLog(){
        loggerInfo.insert(0,"网络请求，访问URL："+url+"\n");
        Logger.d(loggerInfo.toString());

    }

    private String url;
    public void setUrl(String url){
        this.url = url;
    }
    @Override
    public void onError(Call call, Exception e, int id) {
        this.addLog("响应出错："+e.getMessage());
        this.error(call,e,id);
        this.onComplete();
        this.printLog();
    }

    @Override
    public void onResponse(String response, int id) {
        this.addLog("网络请求，访问URL："+url+"\n");
        this.addLog("响应内容："+response);
        this.response = response;
        response(response,id);
        onComplete();
        this.printLog();
    }

    public void onComplete(){

    }

    public void error(Call call,Exception e,int id){

    }
    public void response(String response,int id){

    }

    public ResponseData getResponseData(String response){
        ResponseData responseData = JSON.parseObject(response, ResponseData.class);
        return responseData;
    }
    public <T> T dataTo(Class<T> tClass){
        ResponseData responseData = getResponseData(response);
        JSONObject data = (JSONObject)responseData.getData();
        try {
            T targetObj = tClass.newInstance();
            Utils.copyProperties(data,targetObj);
            return targetObj;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
